import router from "@/router";
import dynamicRouter from '@/router/routerList'
import { menu } from '@/mock/menuTree.js'

const state = {
  // 必须在store里保存一份菜单，store里的值刷新会重置，在router.beforeEach里作为判断条件。
  menu: []
}

const mutations = {
  setMenu(state, list) {
    state.menu = list
  }
}

const actions = {
  generateRoutes({ state }) {
    return new Promise((resolve, reject) => {
      // 请求后台路由数据
      setTimeout(() => {
        let res = menu.data
        let urllist = genMenuUrlArr(res)
        // 动态路由不是一次性的添加，需要每次加载都做添加。也没法转成字符串缓存，不然router-view会不起作用
        let filteredRoutes = genAuthList(dynamicRouter, (it) => urllist.includes(it.path))
        filteredRoutes.forEach(item => {
          // router.addRoute 好像只能添加到一级路由上
          router.addRoute('views', item)
        })
        state.menu = res
        resolve(res)
      }, 500)
    })
  },
}

// 生成菜单url数组
const genMenuUrlArr = function (list, arr = []) {
  list.forEach(li => {
    if (li.url) {
      arr.push(li.url)
    }
    if (li.children && li.children.length) {
      genMenuUrlArr(li.children, arr)
    }
  })
  return arr
}

//递归过滤菜单
const genAuthList = function (tree = [], validate = () => { }, arr = []) {
  if (!tree.length) return []
  for (let item of tree) {
    if (!validate.apply(null, [item])) continue
    let node = { ...item, children: [] }
    arr.push(node)
    if (item.children && item.children.length)
      genAuthList(item.children, validate, node.children)
  }
  return arr
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}